<template>
  <div class="wrap">
    <div class="wrapper">
      <Top :projectId="baojing"></Top>
      <div class="shu-moluai">

<div class="sideba">
     
          <div class="right-sidebar">
            <div class="cewen-bar">人员管理 </div>
            <div class="conn-bar" id="style-1">
             <div class="item-conn lie-bg" @click="zuzhi()" >
                   组织管理
                </div>
                <div class="item-conn lie-bg1" >
                   人员管理
                </div>
                <div class="item-conn lie-bg" @click="yuzhi()" >
                   阈值管理
                </div>
                 <!-- <div class="item-conn lie-bg" @click="shishi()" >
                  实时数据
                </div>
                <div class="item-conn lie-bg" @click="chaobiao()">
                  抄表数据
                </div> -->
                
            </div>
            </div>
        </div>






          <div class="main-dianli-bottom" id="style-1">
             <div class="mainbg-tit">用户管理</div>
             
             <div class="bujv"  style="height:40px">
        <div class="gy-chanxun"  @click="dialogFormVisible = true">新增人员</div>
      </div>
				<!-- 一组结束 -->






				<div class="con-dianvv1"  style=" height:calc(100% - 80px);">
				 <table>
          <tr>
            
            <td class="tuniao">姓名</td>
            <td class="tuniao">用户名</td>
            <td class="tuniao">所属部门</td>
            <!-- <td class="tuniao">性别</td> -->
            <td class="tuniao biaowidth">操作</td>
          </tr>
          <tr v-for="(item,index) in userlist" :key= "index">
            <td v-html="item.name">{{item.name}}</td>
            <td class="lanse">{{item.username}}</td>
            <td class="lvse" >{{item.dept_name}}</td>
            <!-- <td class="huang">{{item.sex}}</td> -->
            <td class="huang">
                <el-button icon=" el-icon-edit" class="xinanniu" @click="editfun(item)"></el-button> 
                <el-popconfirm title="确定删除该信息？" @confirm="delefun(item,index)">
                  <el-button type="danger" icon="el-icon-delete" :disable="dis"  slot="reference"  ></el-button>
                </el-popconfirm>
                <el-button type="warning" icon="el-icon-refresh-left" @click="chongzhifun(item.id)">重置</el-button>
              </td>
          </tr>
        </table>
				</div>


        <el-dialog title="新增人员"  :modal-append-to-body="false" :visible.sync="dialogFormVisible" width="700px" class="my-info-dialog">
        <el-form :model="form" :rules="registerRules" ref="form">
          <el-form-item label="用户名" :label-width="formLabelWidth"  prop="username" class="labyang">
            <el-input v-model="form.username" class="maclass1"></el-input>
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" prop="password"  class="labyang">
            <el-input v-model="form.password" show-password class="maclass1"></el-input>
          </el-form-item>
          <el-form-item label="姓名" :label-width="formLabelWidth"  class="labyang">
            <el-input v-model="form.name" class="maclass1"></el-input>
          </el-form-item>
          <el-form-item label="所属部门" :label-width="formLabelWidth"  prop="deptId"  class="labyang">
             <el-select v-model="form.deptId" placeholder="请选择" @change="qiehuan">
              <el-option
                v-for="item in bumenlist"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="状态" :label-width="formLabelWidth"  class="labyang">
           <el-switch v-model="form.status" :active-text="statusname" @change='statusfun' class="swiyangshi"></el-switch>
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button class="xinanniu"  @click="submitForm('form')">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="修改人员信息"  :modal-append-to-body="false" :visible.sync="dialogeditVisible" width="700px" class="my-info-dialog">
        <el-form :model="editform" :rules="editRules" ref="editform">
          <el-form-item label="用户名" :label-width="formLabelWidth"  prop="username" class="labyang">
            <el-input v-model="editform.username" class="maclass1"></el-input>
          </el-form-item>
          <el-form-item label="姓名" :label-width="formLabelWidth"  class="labyang">
            <el-input v-model="editform.name" class="maclass1"></el-input>
          </el-form-item>
          <el-form-item label="所属部门" :label-width="formLabelWidth"  class="labyang">
             <el-select v-model="editform.deptId" placeholder="请选择" @change="qiehuan1">
              <el-option
                v-for="item in bumenlist"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogeditVisible = false">取 消</el-button>
          <el-button class="xinanniu"  @click="editsubmitForm('editform')">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="重置密码"  :modal-append-to-body="false" :visible.sync="dialogchongzhiVisible" width="600px" class="my-info-dialog">
        <el-form :model="chongzhiform" :rules="chongzhiRules" ref="chongzhiform">
          <el-form-item label="新密码" :label-width="formLabelWidth" prop="newPassword"  class="labyang">
            <el-input v-model="chongzhiform.newPassword" show-password   class="maclass1"></el-input>
          </el-form-item>
          <el-form-item label="再次输入密码" :label-width="formLabelWidth" prop="newPassword2"  class="labyang">
            <el-input v-model="chongzhiform.newPassword2"  class="maclass1" ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogchongzhiVisible = false">取 消</el-button>
          <el-button class="xinanniu"    @click="chongzhisubmitForm('chongzhiform')">确 定</el-button>
        </div>
      </el-dialog>



        <div class="fenye">
                  <el-pagination
                    background
                          @current-change="handleCurrentChange"
                    layout="prev, pager, next"
                    :page-size="pageSize"
                    :total="total" class="fenyone">
                  </el-pagination>
                </div>
				<!-- 右边模块一 -->
				
				
				
			</div>

        <!-- 右边结束 -->
      </div>
    </div>
  </div>
</template>
<script>
import Top from "../../components/common/top.vue";
export default {
  components: { Top },
  data(){
    var validatePass = (rule, value, callback) => {
      const regPhone = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z]).{8,30}')
      if (value == "" || !regPhone.test(value)) {
        callback(new Error('密码必须包含数字和字母，且长度不能少于8位'));
      }else{
        callback();
      }
      };
      var validatetel= (rule, value, callback) =>{
        const regPhone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (value == "" || !regPhone.test(value)) {
        callback(new Error('请输入正确的手机号'));
      }else{
        callback();
      }
      };
       var validatepasstwo = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.chongzhiform.newPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
    return{
       baojing:0,//不想
       total:0,
      pageSize:12,
      current:1,
      currentIndex:0,
      pId:'',
      //{name:"权限",id:"3"},{name:"角色",id:'4'}
      departList:[{name:"组织管理",id:"1"},{name:"用户管理",id:"2"},{name:"阈值管理",id:"5"}],

      
      
      dis:true,
      dialogFormVisible: false,
      form: {
          name: '',
          password: '',
          username: '',
          deptId:''
        },
        formLabelWidth:'100px',
        statusname:'启用',
        registerRules: {
          username:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
          ],
        password: [
          { validator: validatePass,required: true, trigger: 'blur' }
        ],
        // phone: [
        //   { validator: validatetel, trigger: 'blur' }
        // ],
        },
        dialogchongzhiVisible: false,
        chongzhiform: {
          id:'',
          newPassword: '',
          newPassword2: '',
        },
        chongzhiRules: {
        newPassword: [
          { validator: validatePass, trigger: 'blur' }
        ],
        newPassword2: [
          { validator: validatepasstwo, trigger: 'blur' }
        ],
        },
        editform :{
          name: '',
          id:'',
          username: '',
          deptId:''
        },
        dialogeditVisible: false,
       editRules: {
          username:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
          ],
      
        },
       userlist:[],
       bumenlist:[],


     
    }
  },
  beforeDestroy() {
    clearInterval(this.tm2);
  },
  mounted(){
    this.setdeptfun()
    this.setuserfun()
    this.warningfun()
    this.tm2 = setInterval(() => {
      this.warningfun()
    }, 30000);
  },
  methods:{
    qiehuan(e){
      console.log("e",e)
       this.form.deptId = e
      // this.bumenlist.forEach(item =>{
      //   if(item.id==e){
      //     this.form.deptId = e
      //   }
      // })
      
    },
    qiehuan1(e){
      console.log("e",e)
       this.editform.deptId = e
      // this.bumenlist.forEach(item =>{
      //   if(item.id==e){
      //     this.form.deptId = e
      //   }
      // })
      
    },
 renyuan(){
      this.$router.push({path:'/set'})
    },
      zuzhi(){
      this.$router.push({path:'/organization'})
    },
    yuzhi(){
    this.$router.push({path:'/limit'})
    },
    chaobiao(){
      this.$router.push({path:'/meterreading'})
    },
    shishi(){
      this.$router.push({path:'/realtime'})
    },

     editfun(shujv){
      console.log("数据",shujv)
    this.editform.id = shujv.id
    this.editform.username = shujv.username
    this.editform.deptId = shujv.dept
    this.editform.name = shujv.name
    console.log("数据",this.editform)
    this.dialogeditVisible = true
   },
   delefun(shujv,index){
    this.loginLoading = true;
    console.log(shujv.id)
      this.$apiv.deluser({pk:shujv.id}).then((res) => {
        console.log("这个",res.data)
         if(res.code== 2000){
                  this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
                }else{
                  this.$notify.error({
          title: '失败',
          message: '删除失败'
        });}
          this.setuserfun()
          this.loginLoading = false;
        })
        .catch((res) => {
          this.loginLoading = false;
        });
      // this.userlist.splice(index, 1)
   },

   chongzhifun(shujv){
    this.chongzhiform={}
    this.chongzhiform.id= shujv
    this.dialogchongzhiVisible = true
   },
 submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          console.log(valid)
          // @click="dialogFormVisible = false" 
          if (valid) {
          this.form.password=this.$md5(this.form.password)
               console.log('数据', this.form)
              this.loginLoading = true;
              this.$apiv.adduser(this.form).then((res) => {
                console.log("ggg",res.data)
                if(res.code == 0 ){
                  this.$notify({
          title: '成功',
          message: '新增用户成功',
          type: 'success',
          duration: 2000
        })
                }else{
                  this.$notify.error({
          title: '失败',
          message: '添加失败'
        });
                }
                
                this.dialogFormVisible=false
                // this.userlistfun()
                this.setuserfun()
                this.loginLoading = false;
              })
              .catch((res) => {
                this.loginLoading = false;
              });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

       editsubmitForm(formName) {
        this.$refs[formName].validate((valid) => {
          console.log(valid)
          if (valid) {
              console.log('数据', this.editform)
              this.loginLoading = true;
              this.$apiv.edituser(this.editform).then((res) => {
                console.log("222222",res)
                this.dialogeditVisible=false
                 if(res.code == 0){
                  this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
                }else{
                  this.$notify.error({
          title: '失败',
          message: '修改失败'
        });}
                this.setuserfun()
                this.loginLoading = false;
              })
              .catch((res) => {
                this.loginLoading = false;
              });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

       chongzhisubmitForm(formName) {
        this.$refs[formName].validate((valid) => {
          console.log(valid)
          // @click="dialogFormVisible = false" 
          if (valid) {
            console.log('数据', this.chongzhiform)
             this.chongzhiform.newPassword = this.$md5( this.chongzhiform.newPassword)
             this.chongzhiform.newPassword2 = this.$md5( this.chongzhiform.newPassword2)
            this.loginLoading = true;
              this.$apiv.editpass(this.chongzhiform).then((res) => {
                console.log("ggg",res.data)
                 if(res.code == 0 || res.code== 2000){
                  this.$notify({
          title: '成功',
          message: '重置密码成功',
          type: 'success',
          duration: 2000
        })
                }else{
                  this.$notify.error({
          title: '失败',
          message: '重置密码失败'
        });}
                this.dialogchongzhiVisible=false
                // this.userlistfun()
                this.loginLoading = false;
              })
              .catch((res) => {
                this.loginLoading = false;
              });

          } else {
            console.log('error submit!!');
            return false;
          }
        });
        // this.dialogFormVisible=false
      },
      

    warningfun(){
       this.loginLoading = true;
      this.$apiv.warning({}).then((res) => {
        console.log("ggg",res.data)
         if(res.data.is_ok== true){
          this.baojing = 1
        }else{
          this.baojing = 0
        }
          this.loginLoading = false;
        })
        .catch((res) => {
          this.loginLoading = false;
        });
    },
    
    setdeptfun(){
      this.loginLoading = true;
      this.$apiv.setdept({}).then((res) => {
         console.log("99999",res.data.data)
         this.bumenlist=res.data.data
         
          this.loginLoading = false;
        })
        .catch((res) => {
          this.loginLoading = false;
        });
    },
    setuserfun(){
      this.loginLoading = true;
      this.$apiv.setuser({page:this.current,limit:this.pageSize}).then((res) => {
         console.log("888",res)
          this.userlist = res.data.data
           this.total = res.data.total
          this.loginLoading = false;
        })
        .catch((res) => {
          this.loginLoading = false;
        });
    },
    goDepartEquip(index,id){
      this.currentIndex = index
      this.pId = id
      console.log(this.pId)
  
    },
    voltagedetailfun(){
      this.loginLoading = true;
      this.$apiv.voltagedetail({page:this.current,limit:this.pageSize}).then((res) => {
        console.log(res.data)
          this.equipList = res.data.data
					this.total = res.data.total
          this.loginLoading = false;
        })
        .catch((res) => {
          this.loginLoading = false;
        });
    },
     handleCurrentChange(val){
       console.log(`当前页: ${val}`)
      this.current = val
      this.setuserfun()
    },
  },
};
</script>

<style scoped>
@import url("../../../static/zhuti.css");
</style>